// 游戏配置
const TILE_SIZE = 32;
const FARM_WIDTH = 25;
const FARM_HEIGHT = 18;

// DeepSeek R1 API配置
const DEEPSEEK_API_KEY = 'sk-f537433999674801a469368ca758c884';
const DEEPSEEK_API_URL = 'https://api.deepseek.com/v1/chat/completions';

// 游戏状态
const gameState = {
    player: {
        x: 12 * TILE_SIZE,
        y: 9 * TILE_SIZE,
        direction: 'down',
        energy: 100,
        money: 100
    },
    selectedTool: 'hand',
    farm: [],
    inventory: [],
    day: 1,
    season: '春季',
    isMoving: false,
    moveX: 0,
    moveY: 0,
    // 游戏表现跟踪
    performance: {
        actions: {
            till: 0,
            water: 0,
            plant: 0,
            harvest: 0,
            total: 0
        },
        cropsHarvested: 0,
        moneyEarned: 0,
        efficiency: 0,
        lastEvaluationDay: 0
    }
};

// 工具和物品数据
const tools = {
    hand: { name: '空手', energyCost: 0 },
    hoe: { name: '锄头', energyCost: 5 },
    water: { name: '水壶', energyCost: 3 },
    seed: { name: '种子', energyCost: 2 },
    sickle: { name: '镰刀', energyCost: 4 }
};

const crops = {
    parsnip: {
        name: '防风草',
        stages: 4,
        growthTime: 4,
        sellPrice: 35,
        spriteIndex: 0
    },
    potato: {
        name: '土豆',
        stages: 4,
        growthTime: 6,
        sellPrice: 80,
        spriteIndex: 1
    }
};

// DOM元素
let canvas, ctx;
let keys = {};

// 初始化游戏
function init() {
    canvas = document.getElementById('gameCanvas');
    ctx = canvas.getContext('2d');
    
    // 初始化农场
    for (let y = 0; y < FARM_HEIGHT; y++) {
        gameState.farm[y] = [];
        for (let x = 0; x < FARM_WIDTH; x++) {
            gameState.farm[y][x] = {
                isTilled: false,
                isWatered: false,
                hasCrop: false,
                cropType: null,
                growthStage: 0,
                daysWatered: 0
            };
        }
    }
    
    // 初始化背包
    for (let i = 0; i < 12; i++) {
        gameState.inventory[i] = {
            item: null,
            count: 0
        };
    }
    
    // 添加初始种子到背包
    addItemToInventory('parsnip', 10);
    addItemToInventory('potato', 5);
    
    // 初始化UI
    updateUI();
    generateInventorySlots();
    
    // 绑定事件
document.addEventListener('keydown', handleKeyDown);
document.addEventListener('keyup', handleKeyUp);
canvas.addEventListener('click', handleCanvasClick);
canvas.addEventListener('mousemove', function(e) {
    mouseX = e.clientX;
    mouseY = e.clientY;
    render();
});
    
    // 工具按钮事件
    document.getElementById('tool-hand').addEventListener('click', () => selectTool('hand'));
    document.getElementById('tool-hoe').addEventListener('click', () => selectTool('hoe'));
    document.getElementById('tool-water').addEventListener('click', () => selectTool('water'));
    document.getElementById('tool-seed').addEventListener('click', () => selectTool('seed'));
    document.getElementById('tool-sickle').addEventListener('click', () => selectTool('sickle'));
    
    // 日期按钮事件
    document.getElementById('next-day').addEventListener('click', nextDay);
    
    // 开始游戏循环
    setInterval(gameLoop, 1000 / 60);
}

// 游戏循环
function gameLoop() {
    update();
    render();
}

// 更新游戏状态
function update() {
    // 处理玩家移动
    handlePlayerMovement();
    
    // 消耗体力
    if (gameState.isMoving && gameState.player.energy > 0) {
        gameState.player.energy -= 0.02;
        if (gameState.player.energy < 0) gameState.player.energy = 0;
        updateUI();
    }
}

// 渲染游戏
function render() {
    // 清空画布
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    // 绘制农场
    renderFarm();
    
    // 绘制玩家
    renderPlayer();
    
    // 绘制鼠标悬停的格子高亮
    renderHighlightedTile();
}

// 绘制农场
function renderFarm() {
    for (let y = 0; y < FARM_HEIGHT; y++) {
        for (let x = 0; x < FARM_WIDTH; x++) {
            const tile = gameState.farm[y][x];
            const tileX = x * TILE_SIZE;
            const tileY = y * TILE_SIZE;
            
            // 绘制地面
            ctx.fillStyle = '#8D6E63';
            if (tile.isTilled) {
                ctx.fillStyle = '#795548';
                if (tile.isWatered) {
                    ctx.fillStyle = '#5D4037';
                }
            }
            ctx.fillRect(tileX, tileY, TILE_SIZE, TILE_SIZE);
            
            // 绘制作物
            if (tile.hasCrop) {
                ctx.fillStyle = '#4CAF50';
                
                // 根据生长阶段改变作物颜色和大小
                if (tile.growthStage === 1) {
                    ctx.fillStyle = '#66BB6A';
                    ctx.fillRect(tileX + 10, tileY + 10, 12, 12);
                } else if (tile.growthStage === 2) {
                    ctx.fillStyle = '#81C784';
                    ctx.fillRect(tileX + 8, tileY + 8, 16, 16);
                } else if (tile.growthStage === 3) {
                    ctx.fillStyle = '#AED581';
                    ctx.fillRect(tileX + 6, tileY + 6, 20, 20);
                } else if (tile.growthStage === tile.cropType.stages - 1) {
                    ctx.fillStyle = '#FFEB3B'; // 成熟作物
                    ctx.beginPath();
                    ctx.arc(tileX + TILE_SIZE/2, tileY + TILE_SIZE/2, 12, 0, Math.PI * 2);
                    ctx.fill();
                }
            }
        }
    }
}

// 绘制玩家
function renderPlayer() {
    ctx.fillStyle = '#E91E63';
    
    // 简单的玩家图形，根据方向改变
    if (gameState.player.direction === 'down' || gameState.player.direction === 'up') {
        ctx.fillRect(
            gameState.player.x - 8,
            gameState.player.y - 12,
            16,
            24
        );
    } else {
        ctx.fillRect(
            gameState.player.x - 12,
            gameState.player.y - 8,
            24,
            16
        );
    }
}

// 存储鼠标坐标
let mouseX = 0;
let mouseY = 0;

// 绘制高亮的格子
function renderHighlightedTile() {
    // 只有当mouseX和mouseY有效时才渲染高亮格子
    if (mouseX !== undefined && mouseY !== undefined) {
        const rect = canvas.getBoundingClientRect();
        const canvasX = mouseX - rect.left;
        const canvasY = mouseY - rect.top;
        
        const tileX = Math.floor(canvasX / TILE_SIZE);
        const tileY = Math.floor(canvasY / TILE_SIZE);
        
        if (tileX >= 0 && tileX < FARM_WIDTH && tileY >= 0 && tileY < FARM_HEIGHT) {
            ctx.strokeStyle = 'rgba(255, 255, 255, 0.8)';
            ctx.lineWidth = 2;
            ctx.strokeRect(tileX * TILE_SIZE, tileY * TILE_SIZE, TILE_SIZE, TILE_SIZE);
        }
    }
}

// 处理键盘输入
function handleKeyDown(e) {
    keys[e.key] = true;
    gameState.isMoving = true;
}

function handleKeyUp(e) {
    keys[e.key] = false;
    gameState.isMoving = false;
}

// 处理玩家移动
function handlePlayerMovement() {
    const speed = 2;
    let moved = false;
    
    if (keys['ArrowUp'] || keys['w'] || keys['W']) {
        gameState.player.y -= speed;
        gameState.player.direction = 'up';
        moved = true;
    }
    if (keys['ArrowDown'] || keys['s'] || keys['S']) {
        gameState.player.y += speed;
        gameState.player.direction = 'down';
        moved = true;
    }
    if (keys['ArrowLeft'] || keys['a'] || keys['A']) {
        gameState.player.x -= speed;
        gameState.player.direction = 'left';
        moved = true;
    }
    if (keys['ArrowRight'] || keys['d'] || keys['D']) {
        gameState.player.x += speed;
        gameState.player.direction = 'right';
        moved = true;
    }
    
    // 边界检查
    if (gameState.player.x < 0) gameState.player.x = 0;
    if (gameState.player.x > canvas.width) gameState.player.x = canvas.width;
    if (gameState.player.y < 0) gameState.player.y = 0;
    if (gameState.player.y > canvas.height) gameState.player.y = canvas.height;
    
    gameState.isMoving = moved;
}

// 处理画布点击
function handleCanvasClick(e) {
    if (gameState.player.energy <= 0) return;
    
    const rect = canvas.getBoundingClientRect();
    const mouseX = e.clientX - rect.left;
    const mouseY = e.clientY - rect.top;
    
    const tileX = Math.floor(mouseX / TILE_SIZE);
    const tileY = Math.floor(mouseY / TILE_SIZE);
    
    if (tileX >= 0 && tileX < FARM_WIDTH && tileY >= 0 && tileY < FARM_HEIGHT) {
        useTool(tileX, tileY);
    }
}

// 使用工具
function useTool(x, y) {
    const tile = gameState.farm[y][x];
    const tool = tools[gameState.selectedTool];
    
    // 检查体力
    if (gameState.player.energy < tool.energyCost) return;
    
    let actionPerformed = false;
    
    switch (gameState.selectedTool) {
        case 'hoe':
            if (!tile.isTilled && !tile.hasCrop) {
                tile.isTilled = true;
                gameState.player.energy -= tool.energyCost;
                gameState.performance.actions.till++;
                actionPerformed = true;
            }
            break;
        case 'water':
            if (tile.isTilled && !tile.isWatered) {
                tile.isWatered = true;
                tile.daysWatered++;
                gameState.player.energy -= tool.energyCost;
                gameState.performance.actions.water++;
                actionPerformed = true;
            }
            break;
        case 'seed':
            if (tile.isTilled && !tile.hasCrop) {
                // 优先使用背包中有的种子
                let seedToPlant = null;
                
                // 检查是否有防风草种子
                if (hasItemInInventory('parsnip')) {
                    seedToPlant = 'parsnip';
                } 
                // 检查是否有土豆种子
                else if (hasItemInInventory('potato')) {
                    seedToPlant = 'potato';
                }
                
                if (seedToPlant) {
                    tile.hasCrop = true;
                    tile.cropType = crops[seedToPlant];
                    tile.growthStage = 0;
                    tile.isWatered = false;
                    removeItemFromInventory(seedToPlant, 1);
                    gameState.player.energy -= tool.energyCost;
                    gameState.performance.actions.plant++;
                    actionPerformed = true;
                }
            }
            break;
        case 'sickle':
            if (tile.hasCrop && tile.growthStage >= tile.cropType.stages - 1) {
                // 收获作物
                addItemToInventory(tile.cropType.name, 1);
                gameState.player.money += tile.cropType.sellPrice;
                
                // 重置地块
                tile.hasCrop = false;
                tile.cropType = null;
                tile.growthStage = 0;
                
                gameState.player.energy -= tool.energyCost;
                gameState.performance.actions.harvest++;
                gameState.performance.cropsHarvested++;
                gameState.performance.moneyEarned += tile.cropType.sellPrice;
                actionPerformed = true;
            }
            break;
    }
    
    // 更新总操作次数
    if (actionPerformed) {
        gameState.performance.actions.total++;
    }
    
    updateUI();
}

// 选择工具
function selectTool(toolName) {
    gameState.selectedTool = toolName;
    
    // 更新工具按钮状态
    document.querySelectorAll('.tool-buttons button').forEach(btn => {
        btn.classList.remove('active');
    });
    document.getElementById(`tool-${toolName}`).classList.add('active');
}

// 调用DeepSeek API获取游戏评价
async function getGameEvaluation() {
    // 构建性能报告
    const performance = gameState.performance;
    const report = {
        day: gameState.day,
        season: gameState.season,
        totalMoney: gameState.player.money,
        actions: {
            total: performance.actions.total,
            till: performance.actions.till,
            water: performance.actions.water,
            plant: performance.actions.plant,
            harvest: performance.actions.harvest
        },
        cropsHarvested: performance.cropsHarvested,
        moneyEarned: performance.moneyEarned,
        farmEfficiency: performance.actions.total > 0 ? 
            Math.round((performance.actions.harvest / performance.actions.total) * 100) : 0
    };
    
    try {
        const response = await fetch(DEEPSEEK_API_URL, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${DEEPSEEK_API_KEY}`
            },
            body: JSON.stringify({
                "model": "deepseek-chat",
                "messages": [
                    {
                        "role": "system",
                        "content": "你是一个幽默风趣的农场助手，负责评价玩家在农场模拟游戏中的表现。请用生动幽默的语言点评，使用表情符号增加趣味性。评价要积极鼓励，同时可以给出一些小建议。请用中文回复。"
                    },
                    {
                        "role": "user",
                        "content": `请点评玩家在农场游戏中的表现：
日期：${report.season}第${report.day}天
总金钱：${report.totalMoney}金币
今日操作总数：${report.actions.total}
翻土次数：${report.actions.till}
浇水次数：${report.actions.water}
播种次数：${report.actions.plant}
收获次数：${report.actions.harvest}
收获作物总数：${report.cropsHarvested}
今日收入：${report.moneyEarned}金币
农场效率：${report.farmEfficiency}%（收获/总操作）

请用幽默生动的语言评价，给一些鼓励和建议！`
                    }
                ],
                "stream": false
            })
        });
        
        if (!response.ok) {
            throw new Error(`API错误: ${response.status}`);
        }
        
        const data = await response.json();
        return data.choices[0].message.content;
    } catch (error) {
        console.error('获取评价失败:', error);
        // 返回备用评价
        return getBackupEvaluation(report);
    }
}

// 备用评价生成函数（当API调用失败时使用）
function getBackupEvaluation(report) {
    const evaluations = [
        `哎呀，农场助手今天休假啦！不过我还是要夸夸你——${report.season}第${report.day}天，你辛勤劳作了${report.actions.total}次，收获了${report.cropsHarvested}个作物！金币增加了${report.moneyEarned}，继续加油！💪`,
        `农场日报：今日翻土${report.actions.till}次，浇水${report.actions.water}次，播种${report.actions.plant}次，收获${report.actions.harvest}次！虽然助手信号不好，但你的努力我们都看到啦！💰`,
        `农场观察家报告：你的农场效率达到了${report.farmEfficiency}%！虽然今天有点网络波动，但你的农场依然在茁壮发展！🌱`,
        `恭喜你度过了${report.season}第${report.day}天！你的农场管理能力正在稳步提升，继续保持这份热情吧！🌟`,
        `今日农场小结：虽然连接农场总部的信号不太稳定，但你的努力不会被忽视！收获${report.cropsHarvested}个作物，赚了${report.moneyEarned}金币，明天会更好！`
    ];
    
    const randomIndex = Math.floor(Math.random() * evaluations.length);
    return evaluations[randomIndex];
}

// 显示评价
function displayEvaluation(evaluation) {
    const evaluationElement = document.getElementById('evaluation-content');
    evaluationElement.textContent = evaluation;
    
    // 添加动画效果
    evaluationElement.style.opacity = '0';
    setTimeout(() => {
        evaluationElement.style.transition = 'opacity 0.5s ease-in';
        evaluationElement.style.opacity = '1';
    }, 100);
}

// 进入下一天
function nextDay() {
    // 先恢复体力、更新日期和作物生长，避免卡顿
    // 恢复体力
    gameState.player.energy = 100;
    
    // 增加日期
    gameState.day++;
    
    // 季节变化 (每28天一个季节)
    if (gameState.day > 28) {
        gameState.day = 1;
        const seasons = ['春季', '夏季', '秋季', '冬季'];
        const currentIndex = seasons.indexOf(gameState.season);
        gameState.season = seasons[(currentIndex + 1) % seasons.length];
    }
    
    // 更新作物生长
    for (let y = 0; y < FARM_HEIGHT; y++) {
        for (let x = 0; x < FARM_WIDTH; x++) {
            const tile = gameState.farm[y][x];
            
            // 重置浇水状态
            tile.isWatered = false;
            
            // 生长作物
            if (tile.hasCrop && tile.growthStage < tile.cropType.stages - 1) {
                // 只有被浇水的作物才会生长
                if (tile.daysWatered > 0) {
                    tile.growthStage++;
                }
                tile.daysWatered = 0;
            }
        }
    }
    
    // 更新UI
    updateUI();
    
    // 如果有操作记录，异步获取评价
    if (gameState.performance.actions.total > 0 && 
        gameState.performance.lastEvaluationDay !== gameState.day - 1) { // 注意这里使用day-1，因为上面已经增加了day
        
        // 异步获取评价，不阻塞UI
        getGameEvaluation().then(evaluation => {
            displayEvaluation(evaluation);
        }).catch(error => {
            console.error('获取评价失败:', error);
            // 使用备用评价
            const backupEval = getBackupEvaluation({
                day: gameState.day - 1, // 使用前一天的数据
                season: gameState.season,
                totalMoney: gameState.player.money,
                actions: gameState.performance.actions,
                cropsHarvested: gameState.performance.cropsHarvested,
                moneyEarned: gameState.performance.moneyEarned,
                farmEfficiency: gameState.performance.actions.total > 0 ? 
                    Math.round((gameState.performance.actions.harvest / gameState.performance.actions.total) * 100) : 0
            });
            displayEvaluation(backupEval);
        }).finally(() => {
            // 重置每日统计，但保留累计统计
            gameState.performance.lastEvaluationDay = gameState.day - 1; // 使用前一天的数据
            gameState.performance.actions.total = 0;
            gameState.performance.actions.till = 0;
            gameState.performance.actions.water = 0;
            gameState.performance.actions.plant = 0;
            gameState.performance.actions.harvest = 0;
        });
    } else if (gameState.performance.actions.total > 0) {
        // 即使没有评价，也要重置每日统计
        gameState.performance.actions.total = 0;
        gameState.performance.actions.till = 0;
        gameState.performance.actions.water = 0;
        gameState.performance.actions.plant = 0;
        gameState.performance.actions.harvest = 0;
    }
}

// 背包管理
function addItemToInventory(itemName, count) {
    for (let i = 0; i < gameState.inventory.length; i++) {
        if (gameState.inventory[i].item === itemName) {
            gameState.inventory[i].count += count;
            updateInventoryUI();
            return;
        }
    }
    
    // 找一个空槽位
    for (let i = 0; i < gameState.inventory.length; i++) {
        if (gameState.inventory[i].item === null) {
            gameState.inventory[i].item = itemName;
            gameState.inventory[i].count = count;
            updateInventoryUI();
            return;
        }
    }
}

function removeItemFromInventory(itemName, count) {
    for (let i = 0; i < gameState.inventory.length; i++) {
        if (gameState.inventory[i].item === itemName) {
            gameState.inventory[i].count -= count;
            if (gameState.inventory[i].count <= 0) {
                gameState.inventory[i].item = null;
                gameState.inventory[i].count = 0;
            }
            updateInventoryUI();
            return;
        }
    }
}

function hasItemInInventory(itemName) {
    for (let i = 0; i < gameState.inventory.length; i++) {
        if (gameState.inventory[i].item === itemName && gameState.inventory[i].count > 0) {
            return true;
        }
    }
    return false;
}

// 生成背包槽位
function generateInventorySlots() {
    const slotsContainer = document.querySelector('.inventory-slots');
    slotsContainer.innerHTML = '';
    
    for (let i = 0; i < gameState.inventory.length; i++) {
        const slot = document.createElement('div');
        slot.className = 'inventory-slot';
        slot.dataset.index = i;
        
        slotsContainer.appendChild(slot);
    }
    
    updateInventoryUI();
}

// 更新背包UI
function updateInventoryUI() {
    const slots = document.querySelectorAll('.inventory-slot');
    
    for (let i = 0; i < slots.length; i++) {
        const slot = slots[i];
        const item = gameState.inventory[i];
        
        slot.innerHTML = '';
        
        if (item.item) {
            // 创建简单的物品表示
            const itemElement = document.createElement('div');
            itemElement.style.width = '25px';
            itemElement.style.height = '25px';
            itemElement.style.backgroundColor = getRandomColor(item.item);
            itemElement.style.borderRadius = '4px';
            
            slot.appendChild(itemElement);
            
            // 添加数量
            const countElement = document.createElement('div');
            countElement.className = 'item-count';
            countElement.textContent = item.count;
            slot.appendChild(countElement);
        }
    }
}

// 更新游戏UI
function updateUI() {
    document.getElementById('energy').textContent = Math.floor(gameState.player.energy);
    document.getElementById('money').textContent = gameState.player.money;
    document.getElementById('day').textContent = `${gameState.season} 第${gameState.day}天`;
    
    // 当体力为0时禁用操作
    const buttons = document.querySelectorAll('button');
    if (gameState.player.energy <= 0) {
        buttons.forEach(btn => btn.disabled = true);
        document.getElementById('next-day').disabled = false; // 可以睡觉
    } else {
        buttons.forEach(btn => btn.disabled = false);
    }
}

// 辅助函数：根据物品名生成颜色
function getRandomColor(itemName) {
    const colors = {
        parsnip: '#4CAF50',
        potato: '#8D6E63'
    };
    
    return colors[itemName] || '#9E9E9E';
}

// 启动游戏
window.addEventListener('load', init);